package xyz.kail.demo.websocket.spring.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import xyz.kail.demo.websocket.spring.boot.handler.HelloWebSocketHandler;
import xyz.kail.demo.websocket.spring.boot.intercrptor.HelloWebSocketInterceptor;

@EnableWebSocket
@Configuration
public class WebSocketConfiguration implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(echoWebSocketHandler(), "/ws/hello")
                .addInterceptors(helloWebSocketInterceptor())
                .setAllowedOrigins("*")
                .withSockJS()
                // 禁用 WebSocket
                .setWebSocketEnabled(true)
                // 默认 25s
                .setHeartbeatTime(25_000L)
        ;
    }

    @Bean
    public WebSocketHandler echoWebSocketHandler() {
        return new HelloWebSocketHandler();
    }

    @Bean
    public HelloWebSocketInterceptor helloWebSocketInterceptor() {
        return new HelloWebSocketInterceptor();
    }
}